﻿# ------------- #
# Xml Functions #
# ------------- #

# Create or replace xml node
function Get-XmlNode($document, $parent, $node, $name, $prevNode)
{
	if ($node -eq $null)
	{
		if ($prevNode -eq $null)
		{
			$node = $parent.AppendChild($document.CreateElement($name, $document.DocumentElement.NamespaceURI))
		}
		else
		{
			$node = $parent.InsertAfter($document.CreateElement($name, $document.DocumentElement.NamespaceURI), $prevNode);
		}
	}
	elseif ($node.GetType().Name -eq "String")
	{
		$ns = New-Object Xml.XmlNamespaceManager $document.NameTable
		$ns.AddNamespace("ns", $document.DocumentElement.NamespaceURI)
		$xpath = ((Get-XmlNodePath $parent) + "/" + $name).Replace("/", "/ns:")
		$node = $document.SelectSingleNode($xpath, $ns)
		$node = $parent.RemoveChild($node)
		$node = $parent.AppendChild($document.CreateElement($name, $document.DocumentElement.NamespaceURI))
	}
	return $node;
}

# Remove xml node child if exists
function Remove-XmlNodeChild($parent, $name)
{
    $document = $parent.OwnerDocument
    $ns = New-Object Xml.XmlNamespaceManager $document.NameTable
    $ns.AddNamespace("ns", $document.DocumentElement.NamespaceURI)
    $node = $parent.SelectSingleNode("./ns:$name", $ns)
    if ($node -ne $null)
    {
        $node = $parent.RemoveChild($node)
    }
}

# Return full node path
function Get-XmlNodePath($node)
{
	if ($node -eq $null)
	{
		return ""
	}
	if ($node -eq $node.OwnerDocument.DocumentElement)
	{
		return "/" + $node.Name
	}
	else
	{
		return (Get-XmlNodePath $node.ParentNode) + "/" + $node.Name
	}
}